package com.explorati.tree.LeetCode235.BinarySearchTree;

/**
 * LeetCode235 LowestCommonAncestor 
 * 
 * 给定一棵二分搜索树和两个节点，寻找这两个节点的最近公共祖先
 * 
 * @author explorati
 *
 */
public class Solution {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}

	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		assert p != null && q != null;
		
		if (root == null) {
			return null;
		}
		
		if (p.val == root.val || q.val == root.val) {
			return root;
		} else if (p.val > root.val && q.val < root.val) {
			return root;
		} else if (p.val < root.val && q.val > root.val) {
			return root;
		} else if (p.val < root.val && q.val < root.val && root.left != null) {
			return lowestCommonAncestor(root.left, p, q);
		} else if (p.val > root.val && q.val > root.val && root.right != null) {
			return lowestCommonAncestor(root.right, p, q);
		} else {
			return null;
		}
	}
}
